from InterfaceUi import *
from PyQt5.QtWidgets import QApplication,QMainWindow,QMessageBox
from PyQt5 import QtCore, QtGui, QtWidgets
import json
import datetime
import os
import sys
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)
from modules.weather import getWeather 
from modules.ai_qa import  DS
from modules.ai_qa import  DB
from modules.list_manager import ListManager
from modules.emotion_detection import EmoDetector

class interface:
    def __init__(self,MainWindow:Ui_MainWindow):
        self.mainWindow=MainWindow
        self.translate=QtCore.QCoreApplication.translate
        self.flag=0
        self.task_items = {}  # 任务ID到列表项的映射
        self.filename_to_task_id = {}  # 文件名到任务ID的映射
        self.currentCity=""
        self.listManager = ListManager()  # 实例化ListManager
        self.emotion_detector = EmoDetector()  # 实例化EmoDetector
        self.project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # 获取项目根目录
        self.opacity_effect=QtWidgets.QGraphicsOpacityEffect()


    def changeToDS(self):
        self.flag=0
        self.mainWindow.textBrowser_2.clear()
        self.mainWindow.textBrowser_2.append("您好，我是deepseek派来的小助手，请问您有什么问题？\n")
    
    def changeToDB(self):
        self.flag=1
        self.mainWindow.textBrowser_2.clear()
        self.mainWindow.textBrowser_2.append("您好，我是豆包派来的小助手，请问您有什么问题？\n")

    def updatePic(self,cli,frame:QtWidgets.QFrame):
        pic=frame
        if(cli=='晴'):
            frame.setStyleSheet("image:url(:/icons/icons/Sunny.png)")
            return
        if(cli=='阴'):
            frame.setStyleSheet("image:url(:/icons/icons/Yin.png)")
            return
        if(cli=='多云'):
            frame.setStyleSheet("image:url(:/icons/icons/Cloud.png)")
            return
        if(cli=='小雨'):
            frame.setStyleSheet("image:url(:/icons/icons/Little_rain.png)")
            return
        if(cli=='中雨'):
            frame.setStyleSheet("image:url(:/icons/icons/Middle_rain.png)")
            return
        if(cli=='大雨'):
            frame.setStyleSheet("image:url(:/icons/icons/Heavy_rain.png)")
            return


    def get_Weather(self):
        desti=self.mainWindow.lineEdit_search_weather.text()
        getWeather(desti)

        with open('temp/temp.json', 'r') as f:
            data = json.load(f)

        today=data['weatherlist'][0]
        tomorrow=data['weatherlist'][1]
        houtian=data['weatherlist'][2]
        weekday=(today['date'].split('\n'))[0]
        self.mainWindow.label_today_temporature.setText(self.translate("MainWindow", (today['low'].split('℃'))[0]+"~"+(today['high'].split('℃'))[0]+"℃"))
        self.mainWindow.label.setText(self.translate("MainWindow","今天是"+weekday))
        self.mainWindow.label_2.setText(self.translate("MainWindow", datetime.date.today().strftime('%Y年%m月%d日')))
        self.mainWindow.label_today_weather.setText(self.translate("MainWindow", "今天 "+today['climate1']))
        self.mainWindow.label_today_temporature_2.setText(self.translate("MainWindow", (today['low'].split('℃'))[0]+"~"+(today['high'].split('℃'))[0]+"℃"))
        self.mainWindow.label_tomorrow_weather.setText(self.translate("MainWindow", "明天 "+tomorrow['climate1']))
        self.mainWindow.label_tomorrow_temporature.setText(self.translate("MainWindow", (tomorrow['low'].split('℃'))[0]+"~"+(tomorrow['high'].split('℃'))[0]+"℃"))
        self.mainWindow.label_houtian_weather.setText(self.translate("MainWindow", "后天 "+houtian['climate1']))
        self.mainWindow.label_houtian_temporature.setText(self.translate("MainWindow", (houtian['low'].split('℃'))[0]+"~"+(houtian['high'].split('℃'))[0]+"℃"))
        frame1=self.mainWindow.centralwidget.findChild(QtWidgets.QFrame,"frame_today_weather_pic")
        frame2=self.mainWindow.centralwidget.findChild(QtWidgets.QFrame,"frame_Today_weather_pic")
        frame3=self.mainWindow.centralwidget.findChild(QtWidgets.QFrame,"frame_tomorrow_weather_pic")
        frame4=self.mainWindow.centralwidget.findChild(QtWidgets.QFrame,"frame_houtian_weather_pic")
        self.updatePic(today['climate1'],frame1)
        self.updatePic(today['climate1'],frame2)
        self.updatePic(tomorrow['climate1'],frame3)
        self.updatePic(houtian['climate1'],frame4)
        self.currentCity=desti

    def ai_qa(self):
        message=self.mainWindow.lineEdit_input_ask.text()
        if message:
            self.mainWindow.textBrowser_2.append(f"你: {message}")
            self.mainWindow.lineEdit_input_ask.clear()

        try:
                # 根据选择的模型调用相应的API
            if self.flag==0:
                response = DS(message)
            else:
                response = DB(message)

            self.mainWindow.textBrowser_2.append(f"AI: {response}\n")
        except Exception as e:
            self.mainWindow.textBrowser_2.append(f"错误: 调用AI接口失败 - {str(e)}\n")

    def add_task(self):
        task_text = self.mainWindow.lineEdit_input_list.text().strip()
        if task_text:
            try:
                self.listManager.process(task_text)
                self.mainWindow.lineEdit_input_list.clear()
                self.refresh_tasks()
                self.show_message("添加成功！")
            except Exception as e:
                self.show_message(f"添加任务失败：{str(e)}")
    def refresh_tasks(self):
        self.mainWindow.listWidget.clear()
        self.task_items = {}
        self.filename_to_task_id = {}

        todo_dir = os.path.join(self.project_root, "todo_lists")
        print(f"任务列表目录: {todo_dir}")

        if not os.path.exists(todo_dir):
            self.mainWindow.listWidget.addItem("暂无任务")
            self.show_message("暂无任务！")
            return

        try:
            for filename in sorted(os.listdir(todo_dir), reverse=True):
                if filename.endswith('.json'):
                    file_path = os.path.join(todo_dir, filename)
                    try:
                        with open(file_path, 'r', encoding='gbk') as f:
                            task_data = json.load(f)

                        task_id = task_data.get("task_id")
                        if not task_id:
                            print(f"文件 {filename} 缺少task_id字段")
                            continue

                        # 提取文件名中的时间戳部分
                        file_timestamp = filename.replace("task_", "").replace(".json", "")

                        # 保存文件名到任务ID的映射
                        self.filename_to_task_id[file_timestamp] = task_id

                        item = QtWidgets.QListWidgetItem()
                        item.setText(f"{task_data['time']} | {task_data['username']} | {task_data['event']}")
                        item.setData(QtCore.Qt.ItemDataRole.UserRole, task_id)

                        self.mainWindow.listWidget.addItem(item)
                        self.task_items[task_id] = item

                    except Exception as e:
                        print(f"读取任务文件失败 {filename}: {str(e)}")

        except Exception as e:
            self.mainWindow.listWidget.addItem(f"加载任务列表失败: {str(e)}")

    def on_task_selected(self, item):
        self.mainWindow.pushButton_delete.setEnabled(True)

    def delete_selected_task(self):
        selected_items = self.mainWindow.listWidget.selectedItems()
        if not selected_items:
            self.show_message( "请先选择要删除的任务！")
            return

        item = selected_items[0]
        task_id = item.data(QtCore.Qt.ItemDataRole.UserRole)

        if not task_id:
            self.show_message("无法获取任务ID")
            return

        try:
            todo_dir = os.path.join(self.project_root, "todo_lists")

            # 尝试通过任务ID查找文件名
            file_found = False
            file_to_delete = None

            # 方式1: 直接使用任务ID作为文件名
            possible_file1 = os.path.join(todo_dir, f"task_{task_id}.json")
            if os.path.exists(possible_file1):
                file_to_delete = possible_file1
                file_found = True

            # 方式2: 通过文件名到任务ID的映射查找
            if not file_found:
                for filename, stored_task_id in self.filename_to_task_id.items():
                    if stored_task_id == task_id:
                        possible_file2 = os.path.join(todo_dir, f"task_{filename}.json")
                        if os.path.exists(possible_file2):
                            file_to_delete = possible_file2
                            file_found = True
                            break

            # 方式3: 尝试所有文件，查找包含该任务ID的文件
            if not file_found:
                for filename in os.listdir(todo_dir):
                    if filename.endswith('.json'):
                        file_path = os.path.join(todo_dir, filename)
                        try:
                            with open(file_path, 'r', encoding='gbk') as f:
                                data = json.load(f)
                                if data.get("task_id") == task_id:
                                    file_to_delete = file_path
                                    file_found = True
                                    break
                        except:
                            continue

            if not file_found:
                self.show_message(f"找不到任务文件: {task_id}")
                print("当前目录下的文件列表:")
                for f in os.listdir(todo_dir):
                    print(f"- {f}")
                return

            # 删除文件
            os.remove(file_to_delete)
            self.show_message("删除成功！")
            self.refresh_tasks()
            self.mainWindow.pushButton_delete.setEnabled(False)

        except Exception as e:
            self.show_message(f"删除任务失败！: {str(e)}")

        
    def analyze_emotion(self):
        user_input = self.mainWindow.lineEdit_input_emotion.text()
        if(self.currentCity!=""):
            City=self.currentCity
        else:
            City="北京"
        if user_input:
            try:
                result = self.emotion_detector.emotion_detection(
                    user_response=user_input,
                    user_data={"user_id": "default", "name": "用户", "location": City, "age": 25},
                    city=City
                )
                if result and "emotion_analysis" in result:
                    analysis = result["emotion_analysis"]
                    display_text = f"情绪分析结果：\n\n"
                    display_text += f"主要情绪：{analysis.get('emotion', '未知')}\n"
                    display_text += f"情绪强度：{analysis.get('intensity', '未知')}/5\n"
                    display_text += f"置信度：{analysis.get('confidence', 0):.2f}\n"
                    display_text += f"影响因素：{', '.join(analysis.get('contributing_factors', ['未知']))}\n"
                    display_text += f"\n建议：{analysis.get('suggestion', '暂无建议')}"
                    self.mainWindow.textBrowser.setText(display_text)
                else:
                    self.mainWindow.textBrowser.setText("分析失败，请稍后重试")
            except Exception as e:
                self.mainWindow.textBrowser.setText(f"分析出错：{str(e)}")
        else:
            self.mainWindow.textBrowser.setText("请先输入你的心情...")

    def show_message(self, message):
        # 设置消息
        self.mainWindow.label_show.setText(message)
        
        # 创建显示动画
        self.mainWindow.centralwidget.show_animation = QtCore.QPropertyAnimation(self.opacity_effect, b"opacity")
        self.mainWindow.centralwidget.show_animation.setDuration(500)  # 500毫秒
        self.mainWindow.centralwidget.show_animation.setStartValue(0.0)
        self.mainWindow.centralwidget.show_animation.setEndValue(1.0)
        self.mainWindow.centralwidget.show_animation.setEasingCurve(QtCore.QEasingCurve.OutCubic)
        
        # 创建隐藏动画
        self.mainWindow.centralwidget.hide_animation = QtCore.QPropertyAnimation(self.opacity_effect, b"opacity")
        self.mainWindow.centralwidget.hide_animation.setDuration(500)  # 500毫秒
        self.mainWindow.centralwidget.hide_animation.setStartValue(1.0)
        self.mainWindow.centralwidget.hide_animation.setEndValue(0.0)
        self.mainWindow.centralwidget.hide_animation.setEasingCurve(QtCore.QEasingCurve.InCubic)
        
        # 启动显示动画
        self.mainWindow.centralwidget.show_animation.start()
        
        # 1秒后启动隐藏动画
        QtCore.QTimer.singleShot(1000, self.mainWindow.centralwidget.hide_animation.start)

    def set_label_show(self):
        self.mainWindow.label_show.setStyleSheet("""
                            QLabel {
                                color: #ff0000;
                                font-size: 16px;
                                font-family: "幼圆";
                                font-weight: bold;
                                padding: 5px;
                                background-color: rgba(255, 255, 255, 0.8);
                                border-radius: 5px;
                            }
                        """)
        self.opacity_effect = QtWidgets.QGraphicsOpacityEffect(self.mainWindow.label_show)
        self.opacity_effect.setOpacity(0.0)
        self.mainWindow.label_show.setGraphicsEffect(self.opacity_effect)

